package com.huike.utils;

import com.huike.entity.Admin;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;


public class CertificateBulider {


	public String addWaterMark(String[] waterMarkContent, Color markContentColor,
							 Font font) {
		String src=null;
		try {
			File f = new File(this.getClass().getResource(File.separator).getPath());
			/*f=f.getParentFile().getParentFile().getParentFile();*/
			src=f.getParentFile().getParent()+File.separator+"pics";
			File srcImgFile = new File(src+File.separator+"certificate.jpg");
			Image srcImg = ImageIO.read(srcImgFile);
			int srcImgWidth = srcImg.getWidth(null);
			int srcImgHeight = srcImg.getHeight(null);

			BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
			Graphics2D g = bufImg.createGraphics();
			g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
			g.setColor(markContentColor);
			g.setFont(font);

			int[] x = { 400, 400, 370, 400};
			int[] y = { 350, 400, 560, 500};
			Font font2 = new Font("微软雅黑", Font.PLAIN, 20);
			for (int i = 0; i < x.length; i++) {
				if(i>1) {
					g.setFont(font2);
				}
				g.drawString(waterMarkContent[i], x[i], y[i]);
			}
			g.dispose();

			FileOutputStream outImgStream = new FileOutputStream(src+File.separator+"template.jpg");
			ImageIO.setUseCache(false);
			ImageIO.write(bufImg, "jpg", outImgStream);
			outImgStream.flush();
			outImgStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return src;
	}

	public static String  buildCertificate(Admin admin) {
		Font font = new Font("微软雅黑", Font.PLAIN, 25); // 水印字体
		Date d = new Date(admin.getJoinTime().getTime());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		String [] userInfo={admin.getUsername(),admin.getPosition(),sdf.format(d),admin.getUid()};
		Color color = new Color(0, 0, 0); // 水印图片色彩以及透明度

		String src=new CertificateBulider().addWaterMark(userInfo, color, font);
		try{
			FileInputStream stream=new FileInputStream(src+File.separator+"template.jpg");
			return FileUploadUtil.upload(admin.getUid()+".jpg",stream);
		}catch (Exception e){
			e.printStackTrace();
		}
		return src+"\\template.jpg";
	}

}